using Microsoft.EntityFrameworkCore;
using rbac.domain.Entity;
using rbac.domain.Interface;

namespace rbac.domain.Impl;

public class PermissionRepository:IPermissionRepository
{
    private readonly RbacContext _context;

    public PermissionRepository(RbacContext context)
    {
        _context = context;
    }

    public IQueryable<Permission> Permissions()
    {
        return _context.Permissions.AsQueryable().AsNoTracking()
            .Where(p=>p.IsDeleted == false);
    }

    public int Add(Permission entity)
    {
        entity.CreatedTime = DateTime.Now;
        entity.UpdatedTime = DateTime.Now;
        entity.IsDeleted = false;
        _context.Permissions.Add(entity);
        return _context.SaveChanges();
    }

    public int Update(Permission entity)
    {
        var permission = _context.Permissions.FirstOrDefault(p=>p.Id == entity.Id);
        permission.UpdatedTime = DateTime.Now;
        permission.PermissionName = entity.PermissionName;
        permission.PermissionUrl = entity.PermissionUrl;
        permission.Remark = entity.Remark;

        return _context.SaveChanges();
    }

    public int Delete(int loginUserId, params int[]id)
    {
        if (id.Length<=0)
        {
            return 0;
        }

        var permissions = _context.Permissions.Where(p=>id.Contains(p.Id));
        foreach (var permission in permissions)
        {
            permission.IsDeleted = true;
            permission.UpdatedTime = DateTime.Now;
            permission.UpdatedUserId = loginUserId;
        }

        return _context.SaveChanges();
    }
}